package com.solcoo.service;

import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.solcoo.controller.AbstractController;
import com.solcoo.controller.JsonResult;
import com.solcoo.controller.YongHuController;
import com.solcoo.dao.DiJiaJuanDao;
import com.solcoo.dao.UseromrelaDao;
import com.solcoo.dao.YongHuDao;
import com.solcoo.pojo.DiJiaJuan;
import com.solcoo.pojo.Useromrela;
import com.solcoo.pojo.YongHu;

@Service
public class DiJiaJuanService extends AbstractController {

	@Resource
    private DiJiaJuanDao dijiajuandao;
	@Resource
    private YongHuDao yongHuDao;
	@Resource
	private UseromrelaDao useromrelaDao;
	
	private static Logger logger = Logger.getLogger(DiJiaJuanService.class);
	
	/*添加抵用卷*/
	public JsonResult throwExAddDjj(DiJiaJuan dijiajuan, String krshoujih, String isApp) throws Exception {
		YongHu kr = yongHuDao.selectUserByPhone(krshoujih);
		if (kr == null)
            return this.getFailJsonResult("该用户不存在");

		//set 个人id
		dijiajuan.setGerenid(Integer.parseInt(kr.getYonghum()));
        // 查找商户,此处实际为操作员的 用户id（yhm）
        String yhm = dijiajuan.getShanghuid() + "";
        while(yhm.length() < 5) {
            yhm = "0" + yhm;
        }
        YongHu sh = yongHuDao.selectUserByYonghum(yhm);
        dijiajuan.setFaxingren(sh.getYonghum());	
        dijiajuan.setShanghuid(Integer.parseInt(sh.getYonghum()));
        
     // 判断是否为配送员操作
        String employeePh = null;
        if("3".equals(sh.getLeixing())) {
        	Useromrela ur = useromrelaDao.getEnabledEmployee(yhm);
        	if(ur != null) {
        		employeePh = sh.getShoujih();
        		dijiajuan.setShanghuid(Integer.parseInt(ur.getOwnerid()));
     //   		sh = yongHuDao.selectUserByYonghum(ur.getOwnerid());
        	} else {
        		return this.getFailJsonResult("您的客户端已被禁用");
        	}
        }
        if(dijiajuan.getYouxiaoriqi() == null || dijiajuan.getDijiazhi() == null) {
        	return this.getFailJsonResult("抵用值和有效期不能为空");
        }
        
        if(dijiajuan.getDijiazhi() < 1) {
        	return this.getFailJsonResult("抵用值必须大于0");
        }
        
        if(dijiajuan.getYouxiaoriqi().getTime() < (new Date()).getTime()) {
        	return this.getFailJsonResult("不能发行过期抵用卷");
        }
        dijiajuan.setShoudaoriqi(new Date());
        dijiajuan.setKeyong("1");
        dijiajuan.setYixiaofei("0");
        
        dijiajuandao.add(dijiajuan);
        
        String msg = kr.getNicheng() + "(搜卡号：" + kr.getYonghum() + ")\n"
                + "获得抵用卷：" + dijiajuan.getDijiazhi() + "元\n"
        		+ "有效期截至：" + dijiajuan.getYouxiaoriqi().toString();
   
        return this.getSuccessJsonResult(msg);        
	}
	
	/*消费抵用卷*/
	public JsonResult throwExPayDjj(DiJiaJuan dijiajuan, String krshoujih, String isApp) throws Exception {
		YongHu kr = yongHuDao.selectUserByPhone(krshoujih);
		if (kr == null)
            return this.getFailJsonResult("该用户不存在");
		int grYhm = Integer.parseInt(kr.getYonghum());
		if(dijiajuan.getGerenid() != grYhm){
			return this.getFailJsonResult("该用户不持有该抵用卷");
		}
		
        // 查找商户,此处实际为操作员的 用户id（yhm）
        String yhm = dijiajuan.getShanghuid() + "";
        while(yhm.length() < 5) {
            yhm = "0" + yhm;
        }        
        YongHu sh = yongHuDao.selectUserByYonghum(yhm);
        // 判断是否为配送员操作
        String employeePh = null; //用于短信
        if("3".equals(sh.getLeixing())) {
        	Useromrela ur = useromrelaDao.getEnabledEmployee(yhm);
        	if(ur != null) {
        		employeePh = sh.getShoujih();
        		dijiajuan.setHandler(sh.getYonghum());        		
        	} else {
        		return this.getFailJsonResult("您的客户端已被禁用");
        	}
        }       
        
        if(dijiajuan.getKeyong().endsWith("0")) {
        	return this.getFailJsonResult("该抵用卷不可用，已被取消");
        }
        Date youxiaoriqi = dijiajuan.getYouxiaoriqi();
        Date now = new Date();
        if(youxiaoriqi.getTime() < now.getTime()) {
        	return this.getFailJsonResult("该抵用卷已过期，不可使用");
        }
        
        if(dijiajuan.getYixiaofei().endsWith("1")) {
        	return this.getFailJsonResult("该抵用卷已消费掉，不可使用");
        }
         
        Map<String, Object> param = new HashMap<String, Object>();
		param.put("id", dijiajuan.getId());
		param.put("handler", sh.getYonghum());
        /*设置 已使用为 1 by id*/
        dijiajuandao.updateYixiaofei(param);
        
        String msg = kr.getNicheng() + "(搜卡号：" + kr.getYonghum() + ")\n"
                + "使用抵用卷：" + dijiajuan.getDijiazhi() + "元";
   
        return this.getSuccessJsonResult(msg);        
	}
	
	/*取消抵用卷*/
	public JsonResult throwExCancelDjj(DiJiaJuan dijiajuan, String krshoujih, String isApp) throws Exception {
		YongHu kr = yongHuDao.selectUserByPhone(krshoujih);
		if (kr == null)
            return this.getFailJsonResult("该用户不存在");
		int grYhm = Integer.parseInt(kr.getYonghum());
		if(dijiajuan.getGerenid() != grYhm){
			return this.getFailJsonResult("该用户不持有该抵用卷");
		}
        // 查找商户,此处实际为操作员的 用户id（yhm）
        String yhm = dijiajuan.getShanghuid() + "";
        while(yhm.length() < 5) {
            yhm = "0" + yhm;
        }
        YongHu sh = yongHuDao.selectUserByYonghum(yhm);
     // 判断是否为配送员操作
        String employeePh = null;
        if("3".equals(sh.getLeixing())) {
        	Useromrela ur = useromrelaDao.getEnabledEmployee(yhm);
        	if(ur != null) {
        		employeePh = sh.getShoujih();
        		dijiajuan.setHandler(sh.getYonghum());        		
        	} else {
        		return this.getFailJsonResult("您的客户端已被禁用");
        	}
        }       
        
        if(dijiajuan.getKeyong().endsWith("0")) {
        	return this.getFailJsonResult("该抵用卷已被取消,不可再取消");
        }
        Date youxiaoriqi = dijiajuan.getYouxiaoriqi();
        Date now = new Date();
        if(youxiaoriqi.getTime() < now.getTime()) {
        	return this.getFailJsonResult("该抵用卷已过期，不可取消");
        }
        if(dijiajuan.getYixiaofei().endsWith("1")) {
        	return this.getFailJsonResult("该抵用卷已消费掉，不可取消");
        }
        
        Map<String, Object> param = new HashMap<String, Object>();
		param.put("id", dijiajuan.getId());
		param.put("handler", sh.getYonghum());
        /*设置 keyong为 0 by id*/
        dijiajuandao.updateKeyong(param);
        
        String msg = kr.getNicheng() + "(搜卡号：" + kr.getYonghum() + ")\n"
                + "取消抵用卷：" + dijiajuan.getDijiazhi() + "元\n"
                + "抵用卷截至：" + dijiajuan.getYouxiaoriqi().toString() + "\n"
                + "操   作    人：" + dijiajuan.getHandler();
   
        return this.getSuccessJsonResult(msg);        
	}
	
	/*get 所有用户在该商家的 ，有效期内的可消费的， 抵价卷*/
	public Map<String, Object> getKeyongDjj(int shanghuid, int gerenid) throws Exception {
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("gerenid", gerenid);
		param.put("shanghuid", shanghuid);
		
		List<DiJiaJuan> myList = dijiajuandao.queryAllKeyongDjj(param);
		
		Date now = new Date();
		for(DiJiaJuan djj : myList) {
			Date iYouxiao = djj.getYouxiaoriqi();
			if(now.getTime() > iYouxiao.getTime()) {
				myList.remove(djj);
			}
		}
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("djjCount", myList.size());
		map.put("myList", myList);
		map.put("result", true);
		
		return map;
	}
	
	 /*get 用户查看所有 抵价卷, 既用户在该商家的抵价卷历史记录*/
	 public Map<String, Object> getAllDjjSh2Gr(int shanghuid, int gerenid) throws Exception {
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("gerenid", gerenid);
		param.put("shanghuid", shanghuid);
		
		List<DiJiaJuan> myList = dijiajuandao.queryAllDjjSh2Gr(param);
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("djjCount", myList.size());
		map.put("myList", myList);
		map.put("result", true);
		
		return map;
	}
	 
	 /*get 商户查看所有发放的 抵价卷, 既抵价卷历史记录*/
	 public Map<String, Object> getAllDjjBySH(int shanghuid) throws Exception {				
		 List<DiJiaJuan> myList = dijiajuandao.queryAllDjjSh(shanghuid);
		 
		 logger.info("shanghuid: " + shanghuid + " got records count: " + myList.size());
		 Map<String, Object> map = new HashMap<String, Object>();
		 map.put("djjCount", myList.size());
		 map.put("myList", myList);
		 map.put("result", true);
			
		 return map;
	}
}
